import {
  reqShopCartList,
  reqDeleteShopCart,
  reqUpdateCheckedById,
} from "@/api/shopcart";
const state = {
  shopCartList: [],
};
const mutations = {
  //获取购物车的数据
  GETSHOPCART(state, cartList) {
    state.shopCartList = cartList;
  },
};
const actions = {
  //获取购物车的数据
  async getShopCart({ commit }) {
    let res = await reqShopCartList();
    console.log(res);
    if (res.code == 200) {
      commit("GETSHOPCART", res.data);
    }
  },
  //删除购物车数据
  async deleteShopCart({ commit }, skuId) {
    let res = await reqDeleteShopCart(skuId);
    // console.log(res);
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //更新购物车的勾选按钮
  async updateCheckById({ commit }, { skuId, isChecked }) {
    let res = await reqUpdateCheckedById(skuId, isChecked);
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //删除所有勾选按钮的回调
  deleteAllCheckById({ dispatch, getters }) {
    // deleteAllCheckById(context):小仓库
    // console.log(context);
    let promiseAll = [];
    getters.cartList.cartInfoList.forEach((item) => {
      // console.log(123);
      let promise =
        item.isChecked == 1 ? dispatch("deleteShopCart", item.skuId) : "";
      promiseAll.push(promise);
    });
    return Promise.all(promiseAll);
  },
  //点击全选按钮，更改每一条数据的选中状态
  allCheckedChange({ dispatch, state }, isChecked) {
    // console.log(state);
    let promiseAll = [];
    state.shopCartList[0].cartInfoList.forEach((item) => {
      let promise = dispatch("updateCheckById", {
        skuId: item.skuId,
        isChecked,
      });
      promiseAll.push(promise);
    });
    return Promise.all(promiseAll);
  },
};
const getters = {
  cartList(state) {
    return state.shopCartList[0] || {};
  },
};
export default {
  state,
  mutations,
  actions,
  getters,
};
